package com.lh.lock;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;

public class MyAtomic {

    public static void main(String[] args) throws InterruptedException {

//        myAtomicInteger();

//        myLongAdder();



    }

    //比atomicLong性能更好(减少了乐观锁的重试次数)
    private static void myLongAdder() {
        // longAdder只能用于计算加法,且从零开始计算
        LongAdder longAdder = new LongAdder();

        longAdder.increment();
        longAdder.increment();
        longAdder.add(2L);
        System.out.println(longAdder.sum());

        //可以操作加减乘除 
        LongAccumulator longAccumulator = new LongAccumulator((x,y)->{return x + y;},0);

        longAccumulator.accumulate(1);
        longAccumulator.accumulate(3);
        System.out.println(longAccumulator.get());
    }

    private static void myAtomicInteger() throws InterruptedException {
        AtomicInteger i = new AtomicInteger();

        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int j = 0; j < 10; j++) {

                new Thread(()->{

                    try {
                        for (int k = 0; k < 100; k++) {
                            i.getAndIncrement();
                        }
                    } finally {
                        countDownLatch.countDown();
                    }
                },j+"").start();


        }
        //等待10个线程执行完
        //TimeUnit.SECONDS.sleep(2);

        //main线程需等待其他10个执行完
        countDownLatch.await();

        System.out.println("最终结果:"+i.get());
    }

}
